﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace GeneralMethodClass.Text
{
    /// <summary>
    /// 字符串操作
    /// </summary>
    public class StringProcess
    {
        /// <summary>
        /// 拆分字符串。
        /// </summary>
        /// <param name="value">要拆分的字符串。</param>
        /// <param name="delimiterChars">拆分条件。</param>
        /// <returns></returns>
        public static string[] SplitString(string value, char[] delimiterChars)
        {
            return value.Split(delimiterChars);
        }

        /// <summary>
        /// 截取指定长度的子字符串。
        /// </summary>
        /// <param name="value">要截取的字符串。</param>
        /// <param name="len">要截取的长度。</param>
        /// <returns></returns>
        public static string SubString(string value, int len)
        {
            return value != null && value.Length > len ? value.Substring(0, len) : value;
        }

        /// <summary>
        /// 移除空白字符并截取字符串。
        /// </summary>
        /// <param name="value">要操作的字符串。</param>
        /// <param name="lenght">要截取的长度。</param>
        /// <returns></returns>
        public static string TrimString(string value, int lenght)
        {
            if (string.IsNullOrEmpty(value)) return value;
            value = value.Trim();
            return value.Length > lenght ? value.Substring(0, lenght) : value;
        }

        /// <summary>
        /// 判断指定的字符串是否是空引用或是由空白字符组成的字符串。
        /// </summary>
        /// <param name="value">要判断的字符串。</param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(string value)
        {
            return value == null || value.Trim() == string.Empty;
        }

        /// <summary>
        /// 判断指定的字符串是否是空引用或是由空白字符组成的字符串。
        /// </summary>
        /// <param name="value">要判断的字符串。</param>
        /// <param name="name">如果是空串，使用指定的值名称引发值不能为空异常。如果值名称为空引用则不引发异常。</param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(string value, string name)
        {
            if (IsNullOrEmpty(value))
            {
                if (name == null)
                    return true;
                else
                    throw new ValueIsNullOrEmptyException(name);
            }
            else
                return false;
        }

        /// <summary>
        /// 将两个字符串中的值以","分隔，并按顺序以指定的符号连接成为如"value1 = 'valuee'"的形式
        /// </summary>
        /// <param name="value1">前值</param>
        /// <param name="value2">后值</param>
        /// <param name="ch">指定符号</param>
        /// <returns>List</returns>
        public static List<string> FormatString(string value1, string value2, string ch)
        {
            List<string> formatValue = new List<string>();
            char[] c = { ',', '，' };

            string[] v1 = Text.StringProcess.SplitString(value1, c);
            string[] v2 = Text.StringProcess.SplitString(value2, c);

            for (int i = 0; i < v1.Length; i++)
            {
                formatValue.Add(v1[i].Trim() + " = " + ch + v2[i].Trim() + ch);
            }
            
            return formatValue;
        }

        /// <summary>
        /// 用指定的连接符连接字符串数组
        /// </summary>
        /// <param name="value">字符串数组</param>
        /// <param name="connector">连接符</param>
        /// <returns>string</returns>
        public static string ConnectString(List<string> value, string connector)
        {
            string nString = "";

            for (int i = 0; i < value.Count; i++)
            {
                nString += value[i] + connector;
            }

            return StringProcess.SubString(nString, nString.Length - connector.Length);
        }

        /// <summary>
        /// 添加符号
        /// </summary>
        /// <param name="value">要操作的字符串</param>
        /// <param name="addChar">要添加的字符</param>
        /// <returns></returns>
        public static string AddPercent(string value, string addChar)
        {
            return value.EndsWith(addChar) ? value : value + addChar;
        }

        /// <summary>
        /// 哈希字符串。
        /// </summary>
        /// <param name="value">要哈希的字符串。</param>
        /// <returns></returns>
        public static string HashString(string value)
        {
            return Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(value)));
        }

        /// <summary>
        /// 创建 Salt 值。默认数组大小为 4 。
        /// </summary>
        /// <returns></returns>
        public static string CreateSalt()
        {
            return CreateSalt(4);
        }

        /// <summary>
        /// 创建 Salt 值。
        /// </summary>
        /// <param name="size">数组大小。</param>
        /// <returns></returns>
        public static string CreateSalt(int size)
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[size];
            rng.GetBytes(buff);
            return Convert.ToBase64String(buff);
        }

        /// <summary>
        /// 加密连接字符串
        /// Author:TerryLee
        /// From:http://terrylee.cnblogs.com
        /// </summary>
        public static void EncryptConfiguration()
        {
            // 使用什么类型的加密

            string provider = "RsaProtectedConfigurationProvider";

            Configuration config = null;

            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 加密连接字符串

            ConfigurationSection section = config.ConnectionStrings;

            if ((section.SectionInformation.IsProtected == false) &&

                (section.ElementInformation.IsLocked == false))
            {
                section.SectionInformation.ProtectSection(provider);

                section.SectionInformation.ForceSave = true;

                config.Save(ConfigurationSaveMode.Full);

            }
        }

        /// <summary>
        /// 使用正则表达式处理字符串
        /// </summary>
        /// <param name="source">要处理的字符串</param>
        /// <param name="expression">正则表达式</param>
        /// <returns></returns>
        public static string Result(string source, string expression)
        {
            return Regex.Match(source, expression).Value;
        }

        /// <summary>
        /// 判断是否包含正则表达式所提取的字符串
        /// </summary>
        /// <param name="source">要处理的字符串</param>
        /// <param name="expression">正则表达式</param>
        /// <returns></returns>
        public static bool IsContain(string source, string expression)
        {
            return Regex.IsMatch(source, expression);
        }

        /// <summary>
        /// 汉字转换为Unicode编码
        /// </summary>
        /// <param name="str">要编码的汉字字符串</param>
        /// <returns>Unicode编码的的字符串</returns>
        public static string ToUnicode(string str)
        {
            byte[] bts = Encoding.Unicode.GetBytes(str);
            string outStr = "";
            for (int i = 0; i < bts.Length; i += 2) outStr += "\\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
            return outStr;
        }

        /// <summary>
        /// 将Unicode编码转换为汉字字符串
        /// </summary>
        /// <param name="str">Unicode编码字符串</param>
        /// <returns>汉字字符串</returns>
        public static string ToGB2312(string str)
        {
            string outStr = "";
            Regex reg = new Regex(@"(?i)\\u([0-9a-f]{4})");

            outStr = reg.Replace(str, delegate(Match m)
            {
                return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
            });

            return outStr;
        }
    }
}
